/**
 * 入参
 *  type：1-指令新增   2-簿记新增    3-详情  4-交收
    info：type=3||4时，需回填字段
    onRef：组件指针
    getInfo：通过onRef，调用getInfo方法，获取各字段的值，在getInfo中完成校验，若校验不通过，返回undefined
    reset：通过onRef，调用reset方法，清空页面字段
    productOnChange：产品变更事件，输出当前产品ID，若无则为undefined；
    portfolioOnChange：组合变更事件，输出当前组合ID，若无则为undefined；
    tradingcodeOnChange：证券代码变更事件，输出当前证券code，若无则为undefined。
 */
import React, { PureComponent } from 'react';
import { codeType, DATA_ENTRY, FormGroup } from '../../../../comps';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import style from './index.less';
import { connect } from 'dva';
import investmentType from '../../../../utils/enumeratedValues/investmentType';
import { calculateFee } from '../../../../utils/commonFunc';

class OrderFormC extends PureComponent {
  static defaultProps = {
    onRef: () => {},
    portfolioOnChange: () => {},
    productOnChange: () => {},
    tradingcodeOnChange: () => {},
    workStation: false,
  };
  state = {
    info: undefined, //etf详情
    type: undefined, //当前指令的类型type：1-指令新增   2-簿记新增    3-簿记详情
    SecuritiesCode: undefined, //证券代码val值
    bussniessVisible: false, //业务目标编辑补充是否可见
    addSPPIFlag: false, //点击了新增测试按钮
    SPPI_result: undefined, //根据证券代码获取sppi结果
    objectives: undefined, //选中的业务目标
    objectivesEditObj: {}, //缓存每一个业务目标对应的编辑
    editContent: {}, //业务目标编辑内容
    investmentTypeList: [...investmentType], //投资类型下拉
    tradeDirect: '1', //交易方向
    feeData: {
      //费用自动计算条件
      tradingCode: undefined,
      sectype: 'lczr',
      orderside: undefined,
      price: undefined,
    },
  };
  componentDidMount() {
    this.props.onRef(this);
    if (this.props.type == '3' || this.props.type == '4') {
      //详情时取业务目标的值
      this.setState({
        objectives: this.props.info ? this.props.info.bussinessObjectives : undefined,
        editContent: this.props.info || {},
      });
    }
    if (this.props.type == '12') {
      this.setState({ feeData: { ...this.state.feeData, groupId: undefined } });
    } else {
      this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
    }
  }

  //费用自动计算
  changeFee = (type, data) => {
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (this.props.type == 3 || this.props.type == 4) return; //详情不计算
    setTimeout(() => {
      if (data == undefined) {
        setFieldsValue({ fee: undefined });
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: undefined } });
        } else if (type == 'productId') {
          this.setState({ feeData: { ...this.state.feeData, productId: undefined, portfolioid: undefined } });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: undefined } });
        }
      } else {
        if (type == 'tradingCode') {
          this.setState({ feeData: { ...this.state.feeData, tradingCode: data.tradingCode } }, () => {
            let fee = calculateFee(this.state.feeData, this.props.type == 10 || this.props.type == 12 ? true : false);
            fee.then((r) => {
              setFieldsValue({ fee: r });
            });
          });
        } else {
          this.setState({ feeData: { ...this.state.feeData, [type]: data } }, () => {
            let fee = calculateFee(this.state.feeData, this.props.type == 10 || this.props.type == 12 ? true : false);
            fee.then((r) => {
              setFieldsValue({ fee: r });
            });
          });
        }
      }
    }, 100);
  };

  //组合改变
  groupOnChange = (value) => {
    //抛出组合id
    let val;
    if (value) val = value.key;
    this.props.portfolioOnChange(val);
  };
  //产品改变
  productOnChange = (value) => {};

  calculateAmount = (val, type) => {
    const {
      form: { getFieldValue, setFieldsValue },
    } = this.formGroupThis.props;
    let price;
    let amount;
    if (val) {
      if (type != 'amount') {
        price = val;
        amount = getFieldValue('amount');
        setFieldsValue({
          [type]: price * amount,
        });
      } else {
        //数量变更 净价总额 全价总额都进行变更
        amount = val;
        setFieldsValue({
          parValueTotalqj: getFieldValue('priceqj') * amount,
        });
        this.changeFee('price', getFieldValue('priceqj') * amount);
        setFieldsValue({
          parValueTotal: getFieldValue('price') * amount,
        });
      }
    } else {
      setFieldsValue({
        parValueTotalqj: '',
        parValueTotal: '',
      });
      this.changeFee('price', undefined);
    }
  };
  //证券代码切换
  securitiesCodeChange = (value) => {
    const { info } = this.props;
    if (info) return; //详情时不进入判断
    this.setState(
      {
        SecuritiesCode: value,
      },
      () => {
        this.getSPPI_Result();
      },
    );
    this.props.tradingcodeOnChange(value);
  };
  //获取sppi结果
  getSPPI_Result = () => {
    const { SecuritiesCode } = this.state;
    if (this.props.type < 3 || this.props.type == 12) {
      if (!SecuritiesCode) {
        this.setState(
          {
            SPPI_result: undefined,
          },
          () => {
            this.formGroupThis.props.form.setFieldsValue({
              SPPI_result: this.state.SPPI_result,
            });
            this.setSelectList();
          },
        );
        return;
      }
      this.props.dispatch({
        type: 'bondTradeM/getSPPIResult',
        payload: {
          exchangeCode: SecuritiesCode.exchangeCode,
          tradingCode: SecuritiesCode.tradingCode,
        },
        callback: (data) => {
          let temp;
          if (data) {
            //sppi有值 不可点击新增按钮  无值可以
            temp = data.rgpd;
          } else {
            temp = undefined;
          }
          this.setState(
            {
              SPPI_result: temp,
            },
            () => {
              this.formGroupThis.props.form.setFieldsValue({
                SPPI_result: this.state.SPPI_result,
              });
              this.setSelectList();
            },
          );
        },
      });
    }
  };
  //设置投资类型下拉 并确定默认值
  setSelectList = () => {
    // 以收取该金融资产合同现金流量为目的	是	AC
    // 以收取该金融资产合同现金流量为目的	否	FVTPL
    // 以收取该合同现金流量及出售金融资产为目的	是	FVOCI
    // 以收取该合同现金流量及出售金融资产为目的	否	FVTPL
    // 其他	是 or 否	FVTPL
    const { SPPI_result, objectives, tradeDirect } = this.state;
    const {
      form: { setFieldsValue },
    } = this.formGroupThis.props;
    if (tradeDirect == '1') {
      //交易方向为买入
      if (SPPI_result == undefined || objectives == undefined) {
        setFieldsValue({
          investmentType: undefined,
        });
        this.setState({
          investmentTypeList: investmentType,
        });
        return;
      }
      let arr = [];
      if (objectives == 1 && SPPI_result == 1) {
        //AC
        arr = [{ value: 'AC', title: 'AC' }];
        setFieldsValue({
          investmentType: 'AC',
        });
      } else if ((objectives == 1 && SPPI_result == 2) || (objectives == 2 && SPPI_result == 2) || (objectives == 4 && SPPI_result)) {
        //FVTPL
        arr = [{ value: 'FVTPL', title: 'FVTPL' }];
        setFieldsValue({
          investmentType: 'FVTPL',
        });
      } else if (objectives == 2 && SPPI_result == 1) {
        //FVOCI
        arr = [{ value: 'FVOCI', title: 'FVOCI' }];
        setFieldsValue({
          investmentType: 'FVOCI',
        });
      } else {
        arr = [...investmentType];
        setFieldsValue({
          investmentType: undefined,
        });
      }
      this.setState({
        investmentTypeList: [...arr],
      });
    } else if (tradeDirect == '2') {
      //交易方向卖出 请求新的接口
      this.setState({
        investmentTypeList: [...investmentType],
      });
      setTimeout(() => {
        setFieldsValue({
          investmentType: this.props.investmentType,
        });
      }, 500);
    }
  };

  //业绩目标修改
  changeObjectives = (e) => {
    this.setState(
      {
        objectives: e,
      },
      () => {
        this.setSelectList();
      },
    );
  };
  //获取当前表单数据 并校验
  getInfo = () => {
    const {
      user: { currentUser },
    } = this.props;
    const {
      form: { validateFields },
    } = this.formGroupThis.props;
    let query = undefined;
    const { objectives, objectivesEditObj } = this.state;
    let obj = objectivesEditObj[objectives];
    validateFields((err, fieldsValue) => {
      if (!err) {
        query = fieldsValue;
        query.userid = currentUser.userId;
        query.username = currentUser.name;
        query.tradingcode = this.state.SecuritiesCode.tradingCode;
        query.secuabbr = this.state.SecuritiesCode.secuabbr;
        query.exchangeCode = this.state.SecuritiesCode.exchangeCode;
        query.actualRate = query.actualRate ? parseFloat(query.actualRate / 100) : query.actualRate === 0 ? 0 : undefined;
        query.sppiResult = query.SPPI_result; //修改入参名
        if (this.props.type != 10 && this.props.type != 12) query.fee = 0; //交易录入除外 费用计算逻辑未完全梳理清楚，后续用户有真正需求时再添加费用计算相关逻辑
        delete query.SPPI_result;
        delete query.zlxdr;
        delete query.zqdm;
        if (obj) query = { ...query, ...obj };
      }
    });
    return query;
  };
  //重置页面数据 取消
  reset = () => {
    const { form } = this.formGroupThis.props;
    this.props.portfolioOnChange(undefined);
    this.props.tradingcodeOnChange(undefined); //重置组合id和证券代码
    form.resetFields();
    this.setState({
      bussniessVisible: false, //业务目标编辑补充是否可见
      addSPPIFlag: false, //点击了新增测试按钮
      SPPI_result: undefined, //根据证券代码获取sppi结果
      objectives: undefined, //选中的业务目标
      objectivesEditObj: {}, //缓存每一个业务目标对应的编辑
      editContent: {}, //业务目标编辑内容
      investmentTypeList: [...investmentType], //投资类型下拉
      tradeDirect: '1', //交易方向
      SecuritiesCode: undefined,
    });
  };
  // 交易方向改变执行方法
  changeDirect = (e) => {
    this.setState(
      {
        tradeDirect: e.value,
      },
      () => {
        if (this.props.type < 3 || this.props.type == 12) {
          //交易方向改变 对投资类型的影响 1买入 2卖出
          this.setSelectList();
        }
      },
    );
  };

  //form表单渲染
  formRender = () => {
    const {
      type,
      info,
      user: { currentUser },
      workStation,
      wproductid,
      wportfolioid,
    } = this.props;
    const { SPPI_result, SecuritiesCode, investmentTypeList } = this.state;
    const {
      globalM: {
        dataDictionary: { SPPI_USER_DEFINEDTYPE = [] },
      },
    } = this.props;
    const tenant = localStorage.getItem('antd-pro-tenant');

    let disabled;
    if (type == 1 || type == 2 || type == 10 || type == 11 || type == 12) {
      disabled = false;
    } else {
      disabled = true;
    }
    const zlxdr = currentUser.userId + '-' + currentUser.name;
    return (
      <FormGroup
        dataSource={[
          type == 10
            ? {
                dataIndex: 'portfolioid',
                type: DATA_ENTRY.SERIESPRODUCTGROUP,
                initialValue: this.props.listId,
                disabled: true,
                rules: [{ required: true, message: '请选择系列产品!' }],
                span: 24,
              }
            : type == 12
            ? {
                dataIndex: 'productGroupId',
                type: DATA_ENTRY.PRODUCTGROUP,
                rules: [{ required: true, message: '请选择产品组!' }],
                onChange: (e) => {
                  this.props.productGroupOnChange(e?.key); // 向外抛处组合id
                  this.changeFee('groupId', e?.key);
                },
                span: 12,
                tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE'], //不包含估值解析和估值对接的产品
              }
            : {
                title: ['产品', '组合'],
                dataIndex: ['productid', 'portfolioid'],
                type: DATA_ENTRY.PRODUCTGROUPSEP,
                initialValue: workStation ? [wproductid, wportfolioid] : info ? [info.productid, info.portfolioid] : undefined,
                authority: 'write',
                disabled: disabled,
                multipleGroup: false,
                rules: [[{ required: true, message: '请选择产品!' }], [{ required: true, message: '请选择组合!' }]],
                groupOnChange: (e) => {
                  this.groupOnChange(e);
                  this.props.portfolioCode(e ? e.info.portfolioCode : undefined); //向外抛出组合code
                  this.changeFee('portfolioid', e ? e.key : undefined);
                },
                productOnChange: (e) => {
                  this.productOnChange(e);
                  this.props.productCode(e ? e.info.portfolioCode : undefined); //向外抛出产品code
                  this.changeFee('productId', e ? e.key : undefined);
                },
                allowClear: false,
                exist: 1,
                span: 24,
                direction: workStation ? 'columns' : 'row',
                tradeModel: workStation ? undefined : type == 1 || type == 2 ? ['BOOKKEEPING_MODE', 'COMMAND_MODE'] : undefined, //不包含估值解析和估值对接的产品
                workStation: workStation,
              },
          {
            dataIndex: 'zqdm',
            title: '证券代码',
            type: DATA_ENTRY.SECURITIESCODE,
            initialValue: info ? `${info.exchangeCode}-${info.tradingcode}` : undefined,
            onChange: (e) => {
              this.securitiesCodeChange(e);
              this.changeFee('tradingCode', e ? e : undefined);
            },
            codeType: codeType.lczr,
            rules: [{ required: true, message: '请选择证券代码!' }],
            disabled: disabled,
            span: workStation ? 24 : 12,
          },
          {
            title: '交易方向', // 显示名称
            dataIndex: 'direction', // Form识别的Item ID
            type: DATA_ENTRY.TRADINGDIRECT,
            businessType: '6',
            initialValue: info ? info.direction : undefined,
            disabled: disabled,
            onChange: (e) => {
              this.changeDirect(e);
              this.changeFee('orderside', e?.value);
            },
            allowClear: false,
            rules: [{ required: true, message: '请选择交易方向!' }],
            span: workStation ? 24 : 12,
            onRef: (ref) => (this.formGroupThis = ref),
          },
          {
            dataIndex: 'price',
            type: DATA_ENTRY.INPUTNUMBER,
            title: '净价价格',
            unit: '元',
            min: 0,
            max: 999999999999,
            initialValue: info ? info.price : undefined,
            splitStyle: true,
            rules: [{ required: true, message: '请输入净价价格!' }],
            onChange: (val) => this.calculateAmount(val, 'parValueTotal'),
            precision: 4,
            disabled: disabled,
            span: workStation ? 24 : 12,
          },
          {
            dataIndex: 'parValueTotal',
            type: DATA_ENTRY.INPUTNUMBER,
            title: '净价总额',
            unit: '元',
            max: 999999999999,
            initialValue: info ? info.parValueTotal : undefined,
            splitStyle: true,
            rules: [{ required: true, message: '请输入净价总额!' }],
            precision: 4,
            disabled: disabled,
            span: workStation ? 24 : 12,
          },
          {
            dataIndex: 'priceqj',
            title: '全价价格',
            type: DATA_ENTRY.INPUTNUMBER,
            unit: '元',
            min: 0,
            max: 999999999999,
            initialValue: info ? info.priceqj : undefined,
            splitStyle: true,
            rules: [{ required: true, message: '请输入全价价格!' }],
            onChange: (val) => this.calculateAmount(val, 'parValueTotalqj'),
            precision: 4,
            disabled: disabled,
            span: workStation ? 24 : 12,
          },
          {
            dataIndex: 'parValueTotalqj',
            title: '全价总额',
            type: DATA_ENTRY.INPUTNUMBER,
            unit: '元',
            max: 999999999999,
            initialValue: info ? info.parValueTotalqj : undefined,
            splitStyle: true,
            rules: [{ required: true, message: '请输入全价总额!' }],
            precision: 4,
            disabled: disabled,
            span: workStation ? 24 : 12,
          },
          {
            dataIndex: 'amount',
            title: '数量',
            type: DATA_ENTRY.INPUTNUMBER,
            unit: '股',
            precision: 0,
            min: 0,
            max: 999999999999,
            initialValue: info ? info.amount : undefined,
            splitStyle: true,
            onChange: (val) => this.calculateAmount(val, 'amount'),
            rules: [{ required: true, message: '请输入数量!' }],
            disabled: disabled,
            span: workStation ? 24 : 12,
          },
          {
            dataIndex: 'zlxdr',
            type: DATA_ENTRY.INPUT,
            title: '下达人',
            initialValue: info ? info.userid + '-' + info.username : zlxdr,
            rules: [{ required: true, message: '下达人必填' }],
            disabled: true,
            span: workStation ? 24 : 12,
          },
          {
            title: '费用',
            dataIndex: 'fee',
            placeholder: '请输入',
            type: DATA_ENTRY.INPUTNUMBER,
            min: 0,
            precision: 2,
            initialValue: type == '3' || type == '4' ? info.fee : '',
            splitStyle: true,
            disabled: type == '3' || type == '4' ? true : false,
            unit: '元',
            span: workStation ? 24 : 12,
            hide: type == 10 || type == 12 ? false : true, //交易录入和多基金展示费用
          },
          ...(type < 5 || type == 12
            ? [
                {
                  //业务目标
                  dataIndex: 'bussinessObjectives',
                  type: DATA_ENTRY.BUSINESSTARGETC,
                  disabled: type == '3' || type == '4' ? true : false,
                  initialValue: type == '3' || type == '4' ? info?.bussinessObjectives : undefined,
                  onChangeFn: this.changeObjectives,
                  TaretType: type,
                  info: this.state.editContent,
                  getLayerValue: this.getObjectEdit,
                  span: 24,
                },
                {
                  dataIndex: 'SPPI_result',
                  type: DATA_ENTRY.SPPIRESULTC,
                  title: 'SPPI结果',
                  initialValue: type == '3' || type == '4' ? info.sppiResult : undefined,
                  selectProps: {
                    SecuritiesCode,
                    rightContentShow: type < 3 || type == 12 ? true : false, //右侧按钮是否展示，后面展示后的禁用逻辑，展示逻辑，组件控制
                    SPPI_result: SPPI_result, //根据证券代码切换获取SPPI结果
                    SppItype: 3,
                    sppITitle: '新增测试',
                  },
                  onOk: this.getSPPI_Result, //新增完了 重新获取结果
                  span: workStation ? 24 : 12,
                },
                {
                  dataIndex: 'investmentType',
                  type: DATA_ENTRY.SELECT,
                  title: '投资类型',
                  disabled: type == '3' || type == '4' ? true : this.state.tradeDirect == 2 ? true : false,
                  initialValue: type == '3' || type == '4' ? info.investmentType : undefined,
                  dataSource: investmentTypeList,
                  span: workStation ? 24 : 12,
                },
              ]
            : []),

          ...(type < 5 || type == 12
            ? [
                {
                  dataIndex: 'actualRate',
                  type: DATA_ENTRY.INPUTNUMBER,
                  title: '实际利率',
                  unit: '%',
                  min: 0,
                  initialValue: info ? (info.actualRate || info.actualRate == 0 ? parseFloat(info.actualRate * 100) : undefined) : undefined,

                  disabled: disabled,
                  precision: 2,
                  span: workStation ? 24 : 12,
                },
                ...(tenant == 'XAYH'
                  ? [
                      {
                        dataIndex: 'userDefinedType',
                        type: DATA_ENTRY.SELECT,
                        title: '自定义分类',
                        disabled: type == '3' || type == '4' ? true : false,
                        initialValue: type == '3' || type == '4' ? info.userDefinedType : undefined,
                        dataSource: SPPI_USER_DEFINEDTYPE.map((item) => {
                          return { value: item.code, title: item.value };
                        }),
                        span: workStation ? 24 : 12,
                      },
                    ]
                  : []),
              ]
            : []),
          {
            dataIndex: 'remark',
            type: DATA_ENTRY.INPUT,
            title: '备注',
            disabled: disabled,
            initialValue: info ? info.remark : undefined,
            placeholder: '请输入',
            showTextArea: true,
            autosize: { minRows: 2, maxRows: 2 },
            span: 24,
          },
        ]}
        autoLayout={false}
      />
    );
  };
  //存储每一个业绩目标对应的补充编辑
  getObjectEdit = (objectivesEditObj) => {
    this.setState({
      objectivesEditObj,
    });
  };
  render() {
    return <div className={style.info}>{this.formRender()}</div>;
  }
}
export default connect(({ finaFlockingM, globalM, userM: user, loading, bondTradeM }) => ({
  finaFlockingM,
  globalM,
  user,
  loading,
  bondTradeM,
}))(Form.create()(OrderFormC));
